package com.briup.web.controller;

import com.alipay.api.AlipayApiException;


import com.briup.bean.*;


import com.briup.service.IOrderService;
import com.briup.service.IShopCarService;

import com.briup.service.IShopService;

import com.briup.utils.GenerateOrderId;
import com.briup.utils.SumPrice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;


@Controller
public class ConfirmSucController {

    @Autowired
    private IShopCarService shopCarService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private SumPrice sumPrice;

    @GetMapping(value = {"/createOrder"})
    public String pay(Long addressId, String payType, Long[] ids, String sendType,    HttpSession session) throws AlipayApiException {
        //通过ids获取商品名称列表
        List<ShopCar> shopCarList = shopCarService.findShopCars(ids);
        //生成订单编号
        String orderId = "briup" + (GenerateOrderId.getUUIDTOLongNew());
        //计算总金额
        BigDecimal sum = sumPrice.getSumPrice(shopCarList);
        //创建订单并将订单状态设置为未支付
        orderService.saveOrder(ids, (User) session.getAttribute("user"), addressId, orderId, sum);
        //请空购物车下单商品
        shopCarService.deleteShopCarByIds(Arrays.asList(ids));
        //更新库存信息和销量信息
        shopService.updateSalesVolume(shopCarList);
        shopService.updateStockNum(shopCarList);
        //生成支付订单名称
        final String[] subject = {"【杰普官方旗舰店】"};
        shopCarList.forEach(shop -> {
            subject[0] = subject[0] + " " + shop.getShop().getName() + "×" + shop.getNum();
        });
        return "forward:/Alipay?subject="+subject[0]+"&orderId="+orderId+"&sumPrice="+sum;
    }
    @GetMapping(value = {"/confirmOrder"})
    public String confirmOrder(Model model,String out_trade_no) {
        //查到刚刚付款的order
        Order order = orderService.findById(out_trade_no);
        model.addAttribute("order",order);
        return "confirmSuc";
    }
}
